package model

import (
	"gopkg.in/square/go-jose.v1/json"
)

type Monitors struct {
	YL   bool
	WD   bool
	FXFS bool
	SD   bool
	QY   bool
}

type Station struct {
	base    `json:"-" field:"-"`

	StationId            int        `field:"station_id"`
	Name                 string     `field:"name"`
	Code                 string     `field:"code"`
	CityName             string     `field:"city_name"`
	Lat                  int64      `field:"lat"`
	Long                 int64      `field:"long"`
	Env                  string     `field:"env"`
	Address              string     `field:"address"`
	ProvinceName         string     `field:"province_name"`
	Altitude             string     `field:"altitude"`
	Monitor              string     `field:"monitor"`

	Monitors             Monitors       `field:"-"`
	CurrentMinuteMonitor *MonitorMinute `field:"-"`
}

func NewStation() *Station {
	m := new(Station)
	m.init("station")
	return m
}

func (this *Station) GetAll() (list []*Station, err error) {
	res, err := this.DB.FindAll()
	if err != nil || res == nil {
		return
	}
	res.Scan(&list)
	for _, v := range list {
		v.SetMonitors()
	}
	return
}

func (this *Station) GetById(id int) (*Station, error) {
	cond := this.DB.NewCondition()
	cond.SetFilter("station_id", id)
	if v, err := this.DB.SetCondition(cond).FindOne(); err != nil {
		return nil, err
	} else if v == nil {
		return nil, nil
	} else {
		var res Station
		v.Scan(&res)
		res.SetMonitors()
		return &res, nil
	}
}

func (this *Station) Save() error {
	this.init("station")
	if this.StationId == 0 {
		if id, err := this.DB.Insert(this); err != nil {
			return err
		} else {
			this.StationId = id
		}
		return nil
	}
	cond := this.DB.NewCondition().SetFilter("station_id", this.StationId)
	_, err := this.DB.SetCondition(cond).Update(this)
	return err
}

func (this *Station) SetMonitors() {
	var ary []int
	if err := json.Unmarshal([]byte(this.Monitor), &ary); err == nil {
		for i, v := range ary {
			if v == 1 {
				switch i {
				case 0:
					this.Monitors.YL = true
				case 1:
					this.Monitors.WD = true
				case 2:
					this.Monitors.FXFS = true
				case 3:
					this.Monitors.SD = true
				case 4:
					this.Monitors.QY = true
				}
			}
		}
	}
}

func (this *Station) Delete() {
	this.init("station")
	cond := this.DB.NewCondition()
	cond.SetFilter("station_id", this.StationId)
	this.DB.SetCondition(cond).Del()
}

